<template>
  <div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div 
      v-for="(toast, index) in toasts" 
      :key="index"
      class="toast show"
      :class="[getToastClass(toast.type)]"
      role="alert" 
      aria-live="assertive" 
      aria-atomic="true"
    >
      <div class="toast-header">
        <div class="rounded me-2" :class="getIconClass(toast.type)"></div>
        <strong class="me-auto">{{ getToastTitle(toast.type) }}</strong>
        <button 
          type="button" 
          class="btn-close" 
          @click="closeToast(index)"
          aria-label="Close"
        ></button>
      </div>
      <div class="toast-body">
        {{ toast.message }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ToastNotification',
  data() {
    return {
      toasts: [],
      maxToasts: 3
    };
  },
  methods: {
    // 显示一个Toast通知
    show(message, options = {}) {
      const toast = {
        message,
        type: options.type || 'info',
        duration: options.duration || 3000, // 默认3秒
        timestamp: Date.now()
      };
      
      // 将新通知添加到数组顶部
      this.toasts.unshift(toast);
      
      // 限制最大显示数量
      if (this.toasts.length > this.maxToasts) {
        this.toasts.pop();
      }
      
      // 设置自动关闭
      if (toast.duration > 0) {
        setTimeout(() => {
          // 找到并移除这个toast
          const index = this.toasts.findIndex(t => t.timestamp === toast.timestamp);
          if (index !== -1) {
            this.closeToast(index);
          }
        }, toast.duration);
      }
      
      return toast;
    },
    
    // 关闭指定的Toast
    closeToast(index) {
      this.toasts.splice(index, 1);
    },
    
    // 获取Toast的CSS类
    getToastClass(type) {
      switch(type) {
        case 'success': return 'text-bg-success';
        case 'danger': return 'text-bg-danger';
        case 'warning': return 'text-bg-warning';
        case 'info': return 'text-bg-info';
        default: return 'text-bg-light';
      }
    },
    
    // 获取图标CSS类
    getIconClass(type) {
      switch(type) {
        case 'success': return 'bg-success';
        case 'danger': return 'bg-danger';
        case 'warning': return 'bg-warning';
        case 'info': return 'bg-info';
        default: return 'bg-secondary';
      }
    },
    
    // 获取Toast标题
    getToastTitle(type) {
      switch(type) {
        case 'success': return '成功';
        case 'danger': return '错误';
        case 'warning': return '警告';
        case 'info': return '提示';
        default: return '通知';
      }
    }
  }
};
</script>

<style scoped>
.toast-container {
  z-index: 1050;
}

.toast {
  min-width: 250px;
  max-width: 350px;
  margin-bottom: 0.5rem;
  box-shadow: 0 0.25rem 0.75rem rgba(0, 0, 0, 0.1);
  transition: opacity 0.2s ease-out;
}

.rounded {
  width: 18px;
  height: 18px;
}
</style> 